

package com.dog.basics.security.exception;

import cn.hutool.http.HttpStatus;

import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.enums.ExceptionCodeEnum;
import com.dog.basics.common.exception.CustomException;
import com.dog.basics.common.util.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *
 * @date 2018/7/8
 * 客户端异常处理
 * 1. 可以根据 AuthenticationException 不同细化异常处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {
	private final ObjectMapper objectMapper;

	@Override
	@SneakyThrows
	public void commence(HttpServletRequest request, HttpServletResponse response,
						 AuthenticationException authException) {
		response.setCharacterEncoding(CommonConstants.UTF8);
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		R<String> result= null;
		// 异常判断
		if (authException.getCause() instanceof InvalidTokenException){
			//判断无效token
			result = R.failed(ExceptionCodeEnum.FAIL_NOTOKEN.getCode(), ExceptionCodeEnum.FAIL_NOTOKEN.getDescription(),null);
		}else if (authException instanceof InsufficientAuthenticationException){
			// 权限不足
			result = R.failed("无权限访问");
		}else if (authException.getCause() instanceof CustomException){
			// 自定义异常信息
			CustomException customException = (CustomException) authException.getCause();
			result = R.failed(customException.getCode(), customException.getMessage(),null);
		} else if (authException != null) {
			result = R.failed(authException.getMessage());
		}
		response.setStatus(HttpStatus.HTTP_OK);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(objectMapper.writeValueAsString(result));
	}
}
